package commands

import (
	"ant-agent/cmd/config/options"
	"ant-agent/pkg/global"
	"ant-agent/pkg/logger"
	"ant-agent/pkg/pool"
	"ant-agent/pkg/router"
	"context"
	"runtime/debug"

	"github.com/spf13/cobra"
	"sigs.k8s.io/controller-runtime/pkg/manager/signals"
)

func NewServerCommand() *cobra.Command {
	cmd := &cobra.Command{
		Example: `
		# run  the ant-agent-service
		ant-agent
		or
		ant-agent start
		`,
		Use:   cliName,
		Short: "Start the ant-agent",
		RunE: func(cmd *cobra.Command, args []string) error {
			return Run(signals.SetupSignalHandler())
		},
	}
	cmd.ResetFlags()
	return cmd
}

func Run(signalsCtx context.Context) error {
	opt, err := options.NewOptions().TryLoadFromDisk()
	if err != nil {
		return err
	}

	if err = logger.Init(opt.Config.Logopts); err != nil {
		return err
	}

	logger.Info("******************* ant-agent 服务正在启动 *********************")

	ctx, cancelFunc := context.WithCancel(signalsCtx)
	defer cancelFunc()

	defer func() {
		if r := recover(); r != nil {
			stackTrace := string(debug.Stack())
			logger.Error("panic during main execution recover:%v,stackTrace:%v", r, stackTrace)
		}
	}()

	pool, err := pool.NewPoolServiceManager(ctx, *opt)
	if err != nil {
		logger.Error("资源池注册启动失败: %v", err)
		return err
	}
	defer func() {
		if pool != nil {
			pool.Release(ctx)
		}
		logger.Info("******************* ant-agent 退出成功! *********************")
	}()

	go func() {
		if err := router.HttpServerInit().Run(global.HttpAddr); err != nil {
			logger.Error("HTTP服务启动失败:%v", err)
			cancelFunc()
		}
	}()

	logger.Info("******************** ant-agent 服务启动成功! *****************************")

	for {
		select {
		case <-signalsCtx.Done():
			logger.Warn("收到系统退出信号，正在停止 ant-agent ...")
			return nil
		case <-ctx.Done():
			logger.Warn("上下文取消，正在停止 ant-agent ...")
			return nil
		}
	}
}
